import os.path
import cv2


# ---------------------------

def from_video_get_img(video_path):
    print(video_path)
    print(video_path + ' Is Loading...')

    # 创建存放结果图片的文件
    save_file_name = video_path.split('/')[-1].split('.')[0]
    save_fgmask_path = 'Package/Fgmask/' + save_file_name + '/'
    if not os.path.exists(save_fgmask_path):
        os.makedirs(save_fgmask_path)

    # 读取视频
    cap = cv2.VideoCapture(video_path)
    if cap.isOpened():
        # best>MOG
        fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
        fgmask_img_list = []
        id = 0
        flag = True
        while flag:
            ret, frame = cap.read()
            if ret:
                fgmask = fgbg.apply(frame)

                fgmask_img_list.append(fgmask)

                id += 1
                cv2.imshow('frame', fgmask)
                cv2.waitKey(1)
            else:
                break
    cap.release()
    cv2.destroyAllWindows()
    # 写入中间30%-70%的图片张以确保质量
    length = len(fgmask_img_list)
    for i in range(int(length * 0.3), int(length * 0.7) + 1):
        cv2.imwrite(save_fgmask_path + str(i) + '.png', fgmask_img_list[i])


if __name__ == "__main__":
    # 在此强调 video 一定要改名为：名字代号_走路状态_序号.视频类型 的格式，不然程序会报错
    # 如果想要不报错 请修改 save_file_name 这个变量的赋值过程
    # from_video_get_img('video/2/tds_nm_03.MOV')
    from_video_get_img('video/2/tds_nm_03.MOV')